export default {
    namespaced: true, //命名空间
    state: {
        cartList: uni.getStorageSync('cartList') || []
    },
    getters: {
        goPayList(state) {
            return state.cartList.filter(item => item.checked === true)
        },
        totalCount(state, getters) {
            return getters.goPayList.reduce((price, item) => {
                price += item.goods_price * item.nums
                return price
            }, 0)
        },
        totalNums(state, getters) {
            return getters.goPayList.reduce((nums, item) => {
                nums += item.nums
                return nums
            }, 0)
        }
    },
    mutations: {
        cartAdd(state, goodsDetail) {
            // console.log(state, goodsDetail);
            // 类似于 indexOf ，findIndex 存在的话返回它本身的索引，否则返回 -1
            const index = state.cartList.findIndex(item => item.goods_id === goodsDetail.value.goods_id)
            if (index === -1) {
                // 不存在添加新的数据到数组中
                state.cartList.push({...goodsDetail.value, nums: 1, checked: true })
            } else {
                // 存在，只修改当前商品的购买数量
                state.cartList[index].nums++
            }
            // console.log(state.cartList);
            uni.setStorageSync('cartList', state.cartList)
        },
        // 处理单个复选框
        cartGoodsChecked(state, goodsDetail) {
            state.cartList[goodsDetail.index].checked = !state.cartList[goodsDetail.index].checked
            uni.setStorageSync('cartList', state.cartList)
        },
        //商品的数量编辑 利用一个变量的决定-||+ unit
        cartGoodsCount(state, goodsDetail) {
            state.cartList[goodsDetail.index].nums += goodsDetail.unit
            uni.setStorageSync('cartList', state.cartList)
        },
        // 删除商品
        cartGoodsRemove(state, goodsDetail) {
            state.cartList.splice(goodsDetail.index, 1)
            uni.setStorageSync('cartList', state.cartList)
        },
        // 点击全选控制所有小选
        cartAllGoodsChecked(state, goodsDetail) {
            state.cartList.forEach(item => {
                return item.checked = goodsDetail.checked
            });
            uni.setStorageSync('cartList', state.cartList)
        }
    },
    actions: {

    }
}